package handlers

import (
	"ProfessionalCourse5/moni10/cache"
	"ProfessionalCourse5/moni10/modles"
	"ProfessionalCourse5/moni10/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	user := modles.User{
		Username: username,
		Password: password,
	}
	err := modles.DB.Where("username=?", username).Find(&user).Error
	redis_key := "login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"msg":  400,
			"code": "密码错误三次,禁止登录",
		})
		return
	}
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账户错误",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": user,
	})
	return
}

func URAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := modles.UserRole{
		Uid: uid,
		Rid: rid,
	}
	modles.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
	})
	return
}

func RNAdd(c *gin.Context) {
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	data := modles.RoleNode{
		Nid: uid,
		Rid: nid,
	}
	modles.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
	})
	return
}

func URList(c *gin.Context) {
	uid := c.Query("uid")
	var data []modles.Role
	/*
		SELECT
		  *
		FROM
		  roles
		   JOIN user_roles ON roles.id = user_roles.rid
		   WHERE user_roles.uid=1
	*/
	modles.DB.Table("roles").
		Joins("left join user_roles on user_roles.rid=roles.id").
		Where("user_roles.uid=?", uid).Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": data,
	})
	return
}

func RNAList(c *gin.Context) {
	rid := c.Query("rid")
	var data []modles.Node
	/*
		SELECT
		  *
		FROM
		  nodes
		   JOIN role_nodes ON nodes.id = role_nodes.nid
		   WHERE role_nodes.rid=1
	*/
	modles.DB.Table("nodes").
		Joins("JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where("role_nodes.rid=?", rid).Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": data,
	})
	return
}

func CAdd(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	data := modles.Car{
		CarCode: car_code,
		CarName: car_name,
	}
	modles.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
	})
	return
}

func OAdd(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_name := c.PostForm("order_name")
	order_price, _ := strconv.Atoi(c.PostForm("order_price"))
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	data := modles.CarOrder{
		OrderCode:  order_code,
		OrderName:  order_name,
		OrderPrice: order_price,
		Cid:        cid,
	}
	modles.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
	})
	return

}

func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var data []modles.CarOrderList
	/*
		SELECT
		  car_orders.id AS OrderId,
		  car_orders.order_code AS OrderCode,
		  car_orders.order_name AS OrderName,
		  car_orders.order_price AS OrderPrice,
		  cars.car_code AS CarCode,
		  cars.car_name AS CarName
		FROM
		  car_orders
		  LEFT JOIN cars ON car_orders.cid = cars.id
	*/
	redis_key := "list_" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		modles.DB.Offset(offset).Limit(size).
			Table("car_orders").
			Select(
				"car_orders.id AS OrderId",
				"car_orders.order_code AS OrderCode",
				"car_orders.order_name AS OrderName",
				"car_orders.order_price AS OrderPrice",
				"cars.car_code AS CarCode",
				"cars.car_name AS CarName").
			Joins("LEFT JOIN cars ON car_orders.cid = cars.id").Debug().Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &data)
	}

	var total int64
	modles.DB.Model(&modles.CarOrder{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "OK",
		"data":  data,
		"total": total,
	})
}

func CarOrderDetail(c *gin.Context) {
	cid := c.Query("cid")
	var data modles.CarOrderList
	/*
		SELECT
		  car_orders.id AS OrderId,
		  car_orders.order_code AS OrderCode,
		  car_orders.order_name AS OrderName,
		  car_orders.order_price AS OrderPrice,
		  cars.car_code AS CarCode,
		  cars.car_name AS CarName
		FROM
		  car_orders
		  LEFT JOIN cars ON car_orders.cid = cars.id
		WHERE car_orders.cid=1
	*/
	redis_key := "detail_" + cid
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		modles.DB.Table("car_orders").
			Select(
				"car_orders.id AS OrderId",
				"car_orders.order_code AS OrderCode",
				"car_orders.order_name AS OrderName",
				"car_orders.order_price AS OrderPrice",
				"cars.car_code AS CarCode",
				"cars.car_name AS CarName").
			Joins("LEFT JOIN cars ON car_orders.cid = cars.id").
			Where("car_orders.cid=?", cid).Debug().Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &data)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": data,
	})

}
